'''
Created on 2020年3月3日

@author: Administrator
'''
from orm.model import Lottery,db
from view.baseview import BaseView
from flask import json
import random
import time,datetime
from common.public import *

class LotteryView(BaseView):
    def __init__(self):
        pass

    def query(self, params):
        """根据条件取得抽奖列表，params：条件参数"""
        result=[]
        where_condition = True
        
        if params["keyword"]:
            likestr= "%"+params["keyword"] +"%"
            where_condition=(Lottery.name ** likestr )
            where_condition=where_condition | (Lottery.tel ** likestr )
            where_condition=where_condition | (Lottery.company ** likestr )
            where_condition=where_condition | (Lottery.lotteryresult ** likestr )
            where_condition=where_condition | (Lottery.memo** likestr )
        if params["status"]:
            where_condition=where_condition &(Lottery.status.in_(params["status"]))
        if params["date"]:
            likestr= params["date"] 
            where_condition=where_condition & ((Lottery.createdate >= params["date"][0] + " 00:00:00") & (Lottery.createdate <= params["date"][1] + " 23:59:59") )
        total = Lottery.select().where(where_condition).count()
        rows = Lottery.select().where(where_condition).order_by(Lottery.createdate.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows:
            data = {
                "id":row.id,
                "name":row.name,
                "tel":row.tel,
                "company":row.company,
                "memo":row.memo,
                "number":row.number,
                "lotterynumber":row.lotterynumber,
               "createdate":str(row.createdate),
               "lotterydate":str(row.lotterydate),
               "lotteryresult":str(json.loads(row.lotteryresult)),
               "status":row.status
             }
            result.append(data )
        return super().resultSet(200, "", result, total=total)
    
    @db.atomic()                   
    def add(self, params):
        """
        添加
        """
        Lottery.create(
                    name=params["name"],
                    number=params["number"],
                    tel=params["tel"],
                    company=params["company"],
                    memo = params["memo"],
                    status=LOTTERY_UNDO,
                    createdate=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    lotterydate =None,
                    lotteryresult ="[]"
                    )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")         
    @db.atomic()                   
    def update(self, params):
        """
        更新
        """
        rec= Lottery.get(Lottery.id==params["id"])
        rec.name=params["name"]
        rec.number=params["number"]
        rec.tel=params["tel"]
        rec.company=params["company"]
        rec.memo=params["memo"]
        #rec.status=LOTTERY_UNDO
        #rec.createdate= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        #rec.lotterydate=None
        #rec.lotteryresult=""
        #rec.presser= params["presserid"]
        rec.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    
    def getLotteryNumber(self, id):
        """
        取得抽奖次数
        """
        rec= Lottery.get(Lottery.id==id)
        num =rec.number - rec.lotterynumber

        return {"code":200, "message":"抽奖次数取得成功","num":num}  

    def getLottery(self, id):
        """
        抽奖
        """
        
        result =[0,1,2,3,4,5,6,4,0,1] 
        i = int(random.uniform(0,9))
        rec= Lottery.get(Lottery.id==id)
        rec.lotterynumber = rec.lotterynumber + 1
        num = rec.number - rec.lotterynumber
        rec.lotterydate= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if num == 0:
            rec.status= LOTTERY_DONE
        else:
            rec.status= LOTTERY_ING
        lotteryresult =  json.loads(rec.lotteryresult)
        if result[i] == 6:
            lotteryresult.append("一等奖")
        elif result[i] == 5:
            lotteryresult.append("二等奖")
        elif result[i] == 4:
            lotteryresult.append("三等奖")
        elif result[i] == 3 or result[i] == 1:
            lotteryresult.append("四等奖")
        elif result[i] == 0 or result[i] == 2:
            lotteryresult.append("普照奖")
        else:
            lotteryresult.append("普照奖")
        rec.lotteryresult = json.dumps(lotteryresult,ensure_ascii=False)
        rec.save()
            
        return {"code":200, "message":"抽奖次数取得成功","num":num,"result":result[i]}  